﻿using System.Web;
using Jayden.Dll.Web.Enums;
using Jayden.Dll.Web.HtmlControls;

namespace Jayden.Dll.Web.Controls
{
	public class PageHtml : Html
	{
		protected HttpHandlerContext m_Context;

		public HttpHandlerContext Context { get { return m_Context; } }

		public PageHtml() { }

		public override void ProcessHtmlRequest(HttpHandlerContext context)
		{
			Head.Title.InnerText = context.Configuration.GetValue("Website/@name", Head.Title.InnerText);
			m_Context = context;
			LogoutA.LogoutCommandHandler logoutHandler = context.HandlerManager.GetHandler<LogoutA.LogoutCommandHandler>();
			logoutHandler.Logout += new LogoutA.OnLogout(Logout);
			base.ProcessHtmlRequest(context);
			if (context.UserAgent.Type == UserAgentType.InternetExplorer)
			{
				if (context.UserAgent.MajorVersion <= 9)
					Head.ChildControls.Insert(0, new Script("/Scripts/html5shiv.js"));
				if(context.UserAgent.MajorVersion < 9)
					Head.ChildControls.Insert(0, new Script("/Scripts/excanvas.js"));
			}
		}

		private void Logout(HttpHandlerContext context)
		{
			if (context.UriAccess != null && context.UriAccess.Authenticated.HasValue && context.UriAccess.Authenticated.Value)
			{
				Uri uri = new Uri(context.Request.Url);
				if (uri["command"] == "Logout")
					uri["command"] = null;
				if(context.Json != null)
					uri["format"] = null;
				if (context.RequestType == HttpRequestType.Json)
				{
					if (!context.Json.ContainsKey("logoutHref"))
						context.Json.Add("logoutHref", "/login.html?returnUrl=" + HttpUtility.UrlEncode(uri.ToString(true)));
				}
				else if (context.RequestType == HttpRequestType.Html)
					context.Context.Response.Redirect("/login.html?returnUrl=" + HttpUtility.UrlEncode(uri.ToString(true)), true);
			}
		}

		public override void ProcessBinRequest(HttpHandlerContext context)
		{
			m_Context = context;
			base.ProcessBinRequest(context);
		}

		public override void ProcessCssRequest(HttpHandlerContext context)
		{
			m_Context = context;
			base.ProcessCssRequest(context);
		}

		public override void ProcessJsonRequest(HttpHandlerContext context)
		{
			m_Context = context;
			LogoutA.LogoutCommandHandler logoutHandler = context.HandlerManager.GetHandler<LogoutA.LogoutCommandHandler>();
			logoutHandler.Logout += new LogoutA.OnLogout(Logout);
			base.ProcessJsonRequest(context);
		}

		public override void ProcessJsRequest(HttpHandlerContext context)
		{
			m_Context = context;
			base.ProcessJsRequest(context);
		}
	}
}
